﻿using CPPEI.ETL.DataServiceInterface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.ETL.Domain.DataVerification
{
    public class ScriptDataVerification : IDataVerification, IDataVerificationContext
    {
        public string Condition { get; private set; }

        private Noesis.Javascript.JavascriptContext _jsContext;

        public ScriptDataVerification(string condition)
        {
            Condition = condition;
        }

        public void Open()
        {
            _jsContext = new Noesis.Javascript.JavascriptContext();
            try
            {
                _jsContext.Run("1+1");

                return;
            }
            catch(Exception ex)
            {
                _jsContext = new Noesis.Javascript.JavascriptContext();
            }

            try
            {
                _jsContext.Run("1+1");

                return;
            }
            catch (Exception ex)
            {
                _jsContext = new Noesis.Javascript.JavascriptContext();
            }

            try
            {
                _jsContext.Run("1+1");

                return;
            }
            catch (Exception ex)
            {
                _jsContext = null;
            }
        }

        public void Close()
        {
            if(_jsContext != null)
            {
                _jsContext.Dispose();
            }
        }

        public bool Verify(Row row)
        {
            _jsContext.SetParameter("data", row);
            try
            {
                object returnObj = _jsContext.Run(string.Format("{0}", Condition));

                return Convert.ToBoolean(returnObj);
            }
            catch
            {
                return false;
            }
        }
    }
}
